const cloud = require('@cloudbase/node-sdk');

const app = cloud.init({
  env: cloud.SYMBOL_CURRENT_ENV
});

const db = app.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { fileID, metadata } = event;
    
    if (!fileID || !metadata) {
      throw new Error('fileID and metadata are required');
    }

    // 验证必要的元数据字段
    const requiredFields = ['title', 'description', 'artistId', 'category'];
    for (const field of requiredFields) {
      if (!metadata[field]) {
        throw new Error(`${field} is required in metadata`);
      }
    }

    // 创建作品记录
    const artwork = {
      fileID,
      title: metadata.title,
      description: metadata.description,
      artistId: metadata.artistId,
      category: metadata.category,
      tags: metadata.tags || [],
      dimensions: metadata.dimensions || {},
      createdAt: new Date(),
      updatedAt: new Date(),
      status: 'pending', // pending, published, rejected
      likes: 0,
      views: 0
    };

    // 插入数据库
    const result = await db.collection('artworks')
      .add(artwork);

    // 更新艺术家作品计数
    await db.collection('artists')
      .doc(metadata.artistId)
      .update({
        artworkCount: _.inc(1),
        updatedAt: new Date()
      });

    return {
      code: 0,
      data: {
        _id: result.id,
        ...artwork
      },
      message: 'success'
    };
  } catch (error) {
    // 如果出错，尝试删除已上传的文件
    if (event.fileID) {
      try {
        await app.deleteFile({
          fileList: [event.fileID]
        });
      } catch (deleteError) {
        console.error('Failed to delete file:', deleteError);
      }
    }

    return {
      code: 1,
      message: error.message
    };
  }
};